<template>
  <div class="statistics-page">
    <!-- 未设置出差日期提示 -->
    <div v-if="!store.user.tripStartDate" class="no-trip-notice">
      <div class="notice-icon">📊</div>
      <h3>暂无统计数据</h3>
      <p>请先设置出差开始日期</p>
    </div>
    
    <template v-else>
      <!-- 统计卡片 -->
      <div class="stats-overview">
        <!-- 主要统计 -->
        <div class="main-stats">
          <div class="stat-card primary">
            <div class="stat-icon">💼</div>
            <div class="stat-info">
              <span class="stat-value">{{ store.statistics.workDays }}</span>
              <span class="stat-label">工作天数</span>
            </div>
          </div>
          
          <div class="stat-card success">
            <div class="stat-icon">🏖️</div>
            <div class="stat-info">
              <span class="stat-value">{{ store.statistics.restDays }}</span>
              <span class="stat-label">已休息</span>
            </div>
          </div>
        </div>
        
        <!-- 次要统计 -->
        <div class="secondary-stats">
          <div class="stat-item">
            <span class="item-label">应休天数</span>
            <span class="item-value">{{ store.statistics.shouldRestDays }}</span>
          </div>
          <div class="stat-divider"></div>
          <div class="stat-item">
            <span class="item-label">欠休天数</span>
            <span class="item-value" :class="{ 'negative': store.statistics.owedRestDays < 0 }">
              {{ store.statistics.owedRestDays }}
            </span>
          </div>
          <div class="stat-divider"></div>
          <div class="stat-item">
            <span class="item-label">总天数</span>
            <span class="item-value">{{ store.statistics.totalDays }}</span>
          </div>
        </div>
      </div>
      
      <!-- 欠休状态指示 -->
      <div class="owed-status" :class="owedStatusClass">
        <van-icon :name="owedStatusIcon" />
        <span>{{ owedStatusText }}</span>
      </div>
      
      <!-- 设置选项 -->
      <div class="settings-section">
        <van-cell-group inset class="settings-group">
          <van-cell center title="车程计入休息">
            <template #label>
              <span class="cell-desc">休息期间的首尾两天计入休息天数</span>
            </template>
            <template #right-icon>
              <van-switch 
                v-model="includeTravel" 
                size="20" 
                @change="handleTravelChange"
              />
            </template>
          </van-cell>
          
          <van-cell 
            title="统计日期范围" 
            :value="dateRangeText"
            is-link
            @click="showDateRangePicker = true"
          >
            <template #label>
              <span class="cell-desc">点击自定义统计范围</span>
            </template>
          </van-cell>
        </van-cell-group>
      </div>
      
      <!-- 详细统计 -->
      <div class="detail-section">
        <h3 class="section-title">详细统计</h3>
        
        <div class="detail-grid">
          <div class="detail-card">
            <div class="detail-header">
              <span class="detail-icon">📅</span>
              <span class="detail-title">统计周期</span>
            </div>
            <div class="detail-content">
              <div class="detail-row">
                <span>开始日期</span>
                <span>{{ store.statistics.periodStart }}</span>
              </div>
              <div class="detail-row">
                <span>结束日期</span>
                <span>{{ store.statistics.periodEnd }}</span>
              </div>
            </div>
          </div>
          
          <div class="detail-card">
            <div class="detail-header">
              <span class="detail-icon">🚗</span>
              <span class="detail-title">车程统计</span>
            </div>
            <div class="detail-content">
              <div class="detail-row">
                <span>车程天数</span>
                <span>{{ store.statistics.travelDays }} 天</span>
              </div>
              <div class="detail-row">
                <span>计入方式</span>
                <span>{{ includeTravel ? '计入休息' : '不计入' }}</span>
              </div>
            </div>
          </div>
          
          <div class="detail-card full-width">
            <div class="detail-header">
              <span class="detail-icon">📈</span>
              <span class="detail-title">休息比例</span>
            </div>
            <div class="detail-content">
              <div class="progress-bar">
                <div 
                  class="progress-fill" 
                  :style="{ width: restPercentage + '%' }"
                ></div>
              </div>
              <div class="progress-info">
                <span>已休息 {{ store.statistics.restDays }} / 应休 {{ store.statistics.shouldRestDays }}</span>
                <span class="progress-percent">{{ restPercentage }}%</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 休息记录摘要 -->
      <div class="records-summary">
        <h3 class="section-title">休息记录摘要</h3>
        
        <div v-if="store.restRecords.length === 0" class="no-records">
          <span>暂无休息记录</span>
        </div>
        
        <div v-else class="records-list">
          <div 
            v-for="record in recentRecords" 
            :key="record.id"
            class="record-item"
          >
            <div class="record-dates">
              {{ record.startDate }} → {{ record.endDate || '进行中' }}
            </div>
            <div class="record-days">
              {{ getRecordDays(record) }} 天
            </div>
          </div>
          
          <div v-if="store.restRecords.length > 3" class="more-records">
            共 {{ store.restRecords.length }} 条记录
          </div>
        </div>
      </div>
    </template>
    
    <!-- 日期范围选择器 -->
    <van-popup
      v-model:show="showDateRangePicker"
      position="bottom"
      round
      class="date-range-popup"
    >
      <div class="date-range-content">
        <h3>选择统计范围</h3>
        
        <van-cell-group inset class="date-range-form">
          <van-cell 
            title="开始日期" 
            :value="customStartDate || '出差开始日期'"
            is-link
            @click="openDatePicker('start')"
          />
          <van-cell 
            title="结束日期" 
            :value="customEndDate || '今天'"
            is-link
            @click="openDatePicker('end')"
          />
        </van-cell-group>
        
        <div class="date-range-actions">
          <van-button block round plain @click="resetDateRange">
            重置为默认
          </van-button>
          <van-button block round type="primary" @click="applyDateRange">
            应用
          </van-button>
        </div>
      </div>
    </van-popup>
    
    <!-- 日期选择器 -->
    <van-popup
      v-model:show="showDatePicker"
      position="bottom"
      round
      class="date-picker-popup"
    >
      <van-date-picker
        v-model="datePickerValue"
        :title="datePickerTitle"
        :min-date="datePickerMinDate"
        :max-date="datePickerMaxDate"
        @confirm="handleDatePickerConfirm"
        @cancel="showDatePicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { showToast } from 'vant'
import { useAppStore } from '../stores/index.js'

const store = useAppStore()

// 设置
const includeTravel = ref(store.includeTravel)

// 日期范围
const showDateRangePicker = ref(false)
const customStartDate = ref('')
const customEndDate = ref('')

// 日期选择器
const showDatePicker = ref(false)
const datePickerType = ref('start')
const datePickerValue = ref([])
const datePickerTitle = computed(() => 
  datePickerType.value === 'start' ? '选择开始日期' : '选择结束日期'
)
const datePickerMinDate = computed(() => {
  if (store.user.tripStartDate) {
    return new Date(store.user.tripStartDate)
  }
  return new Date(2020, 0, 1)
})
const datePickerMaxDate = computed(() => new Date())

// 计算属性
const dateRangeText = computed(() => {
  if (customStartDate.value && customEndDate.value) {
    return `${customStartDate.value} 至 ${customEndDate.value}`
  }
  return '出差开始至今'
})

const restPercentage = computed(() => {
  if (store.statistics.shouldRestDays === 0) return 0
  const percentage = (store.statistics.restDays / store.statistics.shouldRestDays) * 100
  return Math.min(100, Math.round(percentage))
})

const owedStatusClass = computed(() => {
  if (store.statistics.owedRestDays < 0) return 'surplus'
  if (store.statistics.owedRestDays === 0) return 'balanced'
  return 'owed'
})

const owedStatusIcon = computed(() => {
  if (store.statistics.owedRestDays < 0) return 'smile-o'
  if (store.statistics.owedRestDays === 0) return 'passed'
  return 'warning-o'
})

const owedStatusText = computed(() => {
  if (store.statistics.owedRestDays < 0) {
    return `太棒了！多休了 ${Math.abs(store.statistics.owedRestDays)} 天`
  }
  if (store.statistics.owedRestDays === 0) {
    return '休息刚刚好！'
  }
  return `还需要休息 ${store.statistics.owedRestDays} 天`
})

const recentRecords = computed(() => {
  return [...store.restRecords]
    .sort((a, b) => new Date(b.startDate) - new Date(a.startDate))
    .slice(0, 3)
})

// 处理车程设置变化
const handleTravelChange = async (value) => {
  store.includeTravel = value
  try {
    await store.getStatistics({ 
      includeTravel: value,
      startDate: customStartDate.value || undefined,
      endDate: customEndDate.value || undefined
    })
  } catch (error) {
    showToast({
      message: '更新失败',
      icon: 'fail'
    })
  }
}

// 打开日期选择器
const openDatePicker = (type) => {
  datePickerType.value = type
  const currentDate = type === 'start' ? customStartDate.value : customEndDate.value
  
  if (currentDate) {
    datePickerValue.value = currentDate.split('-')
  } else {
    const today = new Date()
    datePickerValue.value = [
      today.getFullYear().toString(),
      (today.getMonth() + 1).toString().padStart(2, '0'),
      today.getDate().toString().padStart(2, '0')
    ]
  }
  
  showDatePicker.value = true
}

// 处理日期选择确认
const handleDatePickerConfirm = ({ selectedValues }) => {
  const dateStr = selectedValues.join('-')
  
  if (datePickerType.value === 'start') {
    customStartDate.value = dateStr
  } else {
    customEndDate.value = dateStr
  }
  
  showDatePicker.value = false
}

// 重置日期范围
const resetDateRange = () => {
  customStartDate.value = ''
  customEndDate.value = ''
  showDateRangePicker.value = false
  refreshStatistics()
}

// 应用日期范围
const applyDateRange = () => {
  showDateRangePicker.value = false
  refreshStatistics()
}

// 刷新统计
const refreshStatistics = async () => {
  try {
    await store.getStatistics({
      includeTravel: includeTravel.value,
      startDate: customStartDate.value || undefined,
      endDate: customEndDate.value || undefined
    })
  } catch (error) {
    showToast({
      message: '获取统计失败',
      icon: 'fail'
    })
  }
}

// 计算记录天数
const getRecordDays = (record) => {
  if (!record.endDate) {
    const start = new Date(record.startDate)
    const today = new Date()
    const diffTime = today - start
    return Math.max(1, Math.ceil(diffTime / (1000 * 60 * 60 * 24)))
  }
  
  const start = new Date(record.startDate)
  const end = new Date(record.endDate)
  const diffTime = end - start
  return Math.max(1, Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1)
}

// 监听store中的includeTravel变化
watch(() => store.includeTravel, (newVal) => {
  includeTravel.value = newVal
})
</script>

<style scoped>
.statistics-page {
  padding: 16px;
  padding-bottom: 80px;
}

/* 未设置出差提示 */
.no-trip-notice {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  text-align: center;
}

.notice-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.no-trip-notice h3 {
  color: var(--text-primary);
  margin-bottom: 8px;
}

.no-trip-notice p {
  color: var(--text-muted);
  font-size: 14px;
}

/* 统计概览 */
.stats-overview {
  margin-bottom: 16px;
}

.main-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-bottom: 12px;
}

.stat-card {
  background: var(--card-bg);
  border-radius: 16px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.stat-card.primary {
  border: 1px solid rgba(99, 102, 241, 0.3);
  background: rgba(99, 102, 241, 0.1);
}

.stat-card.success {
  border: 1px solid rgba(16, 185, 129, 0.3);
  background: rgba(16, 185, 129, 0.1);
}

.stat-icon {
  font-size: 32px;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: var(--text-primary);
  line-height: 1.2;
}

.stat-label {
  font-size: 13px;
  color: var(--text-secondary);
}

.secondary-stats {
  background: var(--card-bg);
  border-radius: 12px;
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.item-label {
  font-size: 12px;
  color: var(--text-muted);
}

.item-value {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.item-value.negative {
  color: var(--success-color);
}

.stat-divider {
  width: 1px;
  height: 32px;
  background: var(--border-color);
}

/* 欠休状态 */
.owed-status {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 14px;
  border-radius: 12px;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 16px;
}

.owed-status.surplus {
  background: rgba(16, 185, 129, 0.15);
  color: var(--success-color);
}

.owed-status.balanced {
  background: rgba(99, 102, 241, 0.15);
  color: var(--accent-primary);
}

.owed-status.owed {
  background: rgba(245, 158, 11, 0.15);
  color: var(--warning-color);
}

/* 设置区域 */
.settings-section {
  margin-bottom: 20px;
}

.settings-group {
  background: transparent !important;
}

.settings-group :deep(.van-cell) {
  background: var(--card-bg) !important;
  margin-bottom: 8px;
  border-radius: 12px;
}

.settings-group :deep(.van-cell__title) {
  color: var(--text-primary);
}

.settings-group :deep(.van-cell__value) {
  color: var(--accent-primary);
}

.cell-desc {
  font-size: 12px;
  color: var(--text-muted);
}

/* 详细统计 */
.detail-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 12px;
  padding-left: 4px;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.detail-card {
  background: var(--card-bg);
  border-radius: 12px;
  padding: 16px;
}

.detail-card.full-width {
  grid-column: span 2;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.detail-icon {
  font-size: 18px;
}

.detail-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
}

.detail-row span:first-child {
  color: var(--text-muted);
}

.detail-row span:last-child {
  color: var(--text-primary);
  font-weight: 500;
}

/* 进度条 */
.progress-bar {
  height: 8px;
  background: var(--card-bg-hover);
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: var(--accent-gradient);
  border-radius: 4px;
  transition: width 0.3s ease;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: var(--text-muted);
  margin-top: 8px;
}

.progress-percent {
  color: var(--accent-primary);
  font-weight: 600;
}

/* 休息记录摘要 */
.records-summary {
  margin-bottom: 20px;
}

.no-records {
  background: var(--card-bg);
  border-radius: 12px;
  padding: 24px;
  text-align: center;
  color: var(--text-muted);
}

.records-list {
  background: var(--card-bg);
  border-radius: 12px;
  overflow: hidden;
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 16px;
  border-bottom: 1px solid var(--border-color);
}

.record-item:last-child {
  border-bottom: none;
}

.record-dates {
  font-size: 14px;
  color: var(--text-primary);
}

.record-days {
  font-size: 14px;
  font-weight: 600;
  color: var(--accent-primary);
}

.more-records {
  padding: 12px 16px;
  text-align: center;
  font-size: 13px;
  color: var(--text-muted);
  background: var(--card-bg-hover);
}

/* 日期范围弹窗 */
.date-range-popup {
  background: var(--card-bg) !important;
}

.date-range-content {
  padding: 24px;
}

.date-range-content h3 {
  text-align: center;
  color: var(--text-primary);
  margin-bottom: 20px;
}

.date-range-form {
  background: transparent !important;
  margin-bottom: 20px;
}

.date-range-form :deep(.van-cell) {
  background: var(--card-bg-hover) !important;
  margin-bottom: 8px;
  border-radius: 8px;
}

.date-range-form :deep(.van-cell__title) {
  color: var(--text-secondary);
}

.date-range-form :deep(.van-cell__value) {
  color: var(--text-primary);
}

.date-range-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 日期选择器弹窗 */
.date-picker-popup {
  background: var(--card-bg) !important;
}

.date-picker-popup :deep(.van-picker) {
  background: var(--card-bg) !important;
}

.date-picker-popup :deep(.van-picker__toolbar) {
  background: var(--card-bg);
}

.date-picker-popup :deep(.van-picker__title) {
  color: var(--text-primary);
}

.date-picker-popup :deep(.van-picker__confirm) {
  color: var(--accent-primary);
}

.date-picker-popup :deep(.van-picker__cancel) {
  color: var(--text-muted);
}

.date-picker-popup :deep(.van-picker-column__item) {
  color: var(--text-secondary);
}

.date-picker-popup :deep(.van-picker-column__item--selected) {
  color: var(--text-primary);
}
</style>

